/**
 * Copyright (c) 2011, 2012 Sentaca Communications Ltd.
 */
package yoyo.secret.app.widget;

import java.util.concurrent.atomic.AtomicBoolean;

import yoyo.secret.app.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Interpolator;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

public class ToggleImageButton extends ImageView {

	private int imageOn;
	private int imageOff;
	private AtomicBoolean on = new AtomicBoolean(false);
	private Animation animation = null;

	public ToggleImageButton(Context context, AttributeSet attrs) {
		super(context, attrs);

		if (attrs != null) {
			TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.image_labeled_button, 0, 0);
			imageOn = a.getResourceId(R.styleable.image_labeled_button_icon_resource, 0);
			a = context.obtainStyledAttributes(attrs, R.styleable.toggle_image_labeled_button, 0, 0);
			imageOff = a.getResourceId(R.styleable.toggle_image_labeled_button_icon_resource_off, 0);
			setImageResource(imageOff);
			a.recycle();
		}

		animation = new RotateAnimation(0, 359, 33, 33);
		animation.setInterpolator(getContext(), android.R.anim.accelerate_decelerate_interpolator);
		animation.setDuration(500);
		animation.setFillAfter(true);
		animation.setFillEnabled(true);
	}

	private void handleNewState(boolean newState) {
		startAnimation(animation);
		if (newState) {
			setImageResource(imageOn);
		} else {
			setImageResource(imageOff);
		}
	}

	@Override
	public void setOnClickListener(final OnClickListener l) {
		OnClickListener wrappingListener = new OnClickListener() {

			public void onClick(View v) {
				boolean newState = !on.get();
				on.set(newState);
				handleNewState(newState);
				l.onClick(v);
			}

		};

		super.setOnClickListener(wrappingListener);
	}

	public boolean getButtonState() {
		return on.get();
	}

	public void setState(boolean b) {
		on.set(b);
		handleNewState(b);
	}

}
